package com.rn.gypsophila.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.Scanner;

@Slf4j
@Service
public class ChatClient {

    @Value("${cserver.bind_address}")
    private String host;

    @Value("${cserver.bind_port}")
    private Integer port;

    private EventLoopGroup eventLoopGroup;
    private ChannelFuture channelFuture;

    @PostConstruct
    public void init() throws InterruptedException {
        eventLoopGroup = new NioEventLoopGroup();
       try {
           Bootstrap bootstrap = new Bootstrap().group(eventLoopGroup)
                   .channel(NioSocketChannel.class)
                   .option(ChannelOption.SO_KEEPALIVE, true)
                   .handler(new ChatClientInitializer())
                   .remoteAddress(host, port);
           channelFuture = bootstrap.connect().sync();
           Channel channel = channelFuture.channel();
           log.info("---------------" + channel.remoteAddress() + "---------------");
           Scanner scanner = new Scanner(System.in);
           while(scanner.hasNextLine()){
               channel.writeAndFlush(scanner.nextLine() + "\r\n");
           }
       } finally {
           eventLoopGroup.shutdownGracefully();
       }
    }

    @PreDestroy
    public void shutdown() throws InterruptedException {
        log.info("正在停止客户端");
        try {
            channelFuture.channel().closeFuture().sync();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
        log.info("客户端已停止!");
    }

}
